package com.fbee.smartcommunities.service.impl;

import com.fbee.smartcommunities.entity.Cart;
import com.fbee.smartcommunities.entity.Orders;
import com.fbee.smartcommunities.mapper.OrdersMapper;
import com.fbee.smartcommunities.service.OrderGoodsService;
import com.fbee.smartcommunities.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fbee.smartcommunities.utils.CustomizeException;
import com.fbee.smartcommunities.utils.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Random;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 汪佳泉
 * @since 2024-08-27
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Resource
    private OrderGoodsService orderGoodsService;

    @Override
    @Transactional
    public Boolean createOrder(Long[] id,
                               Long[] goodId,
                               Integer[] count,
                               Long openId,
                               String linkUser,
                               String linkAddress,
                               String linkPhone,
                               BigDecimal totalPrice,
                               String payType) {
        // 先生成一个订单编号
        if(id == null){
            id = new Long[1];
            id[0] = new Long(LocalDateTime.now().getSecond());
        }
        if(payType == null){
            payType = "我的余额";
        }
        String number = StringUtil.generateOrderNumber(openId.intValue(), id[0].intValue(), new Random().nextInt(10));
        Orders order = new Orders(number, totalPrice, openId, linkUser, linkPhone, linkAddress, "待支付", LocalDateTime.now(),payType);
        this.save(order);
        for (int i = 0;i<goodId.length;i++) {
            orderGoodsService.add(new Long(order.getId()),goodId[i],count[i]);
        }
        return true;
    }

}
